//
//  SoundTool.m
//  NewGame
//
//  Created by wwj on 15/9/22.
//  Copyright © 2015年 wwj. All rights reserved.
//

#import "SoundTool.h"
#import <AVFoundation/AVFoundation.h>

@interface SoundTool ()
@property (strong, nonatomic) AVAudioPlayer *bgMusicPlayer;
@property (strong, nonatomic) NSMutableDictionary *soundIDs;
@end

@implementation SoundTool

+(SoundTool *)sharedSoundTool{
    static SoundTool *soundTool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        soundTool = [[SoundTool alloc] init];
    });
    
    return soundTool;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        [self loadBgMusic];
        [self loadSounds];
        
        _musicMuted = [[NSUserDefaults standardUserDefaults] boolForKey:kMusicMuted];
        _soundMuted = [[NSUserDefaults standardUserDefaults] boolForKey:kSoundMuted];
    }
    return self;
}


-(void)setMusicMuted:(BOOL)musicMuted{
    _musicMuted = musicMuted;
    [[NSUserDefaults standardUserDefaults] setBool:musicMuted forKey:kMusicMuted];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (musicMuted) {
        [_bgMusicPlayer pause];
    }else{
        [_bgMusicPlayer play];
    }
    
}

-(void)setSoundMuted:(BOOL)soundMuted{
    _soundMuted = soundMuted;
    [[NSUserDefaults standardUserDefaults] setBool:soundMuted forKey:kSoundMuted];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


#pragma mark 加载背景音乐
- (void)loadBgMusic{
    //加载播放器
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"bg_music.mp3" withExtension:nil];
    AVAudioPlayer *bgMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    
    //缓冲
    [bgMusicPlayer prepareToPlay];
    
    //循环播放
    bgMusicPlayer.numberOfLoops = -1;
    _bgMusicPlayer = bgMusicPlayer;
}

- (void)loadSounds{
    _soundIDs = [NSMutableDictionary dictionary];
    
    NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"sound" withExtension:@"bundle"];
    NSBundle *soundBundle = [NSBundle bundleWithURL:bundleURL];
    
    // 3.获得sound.bundle中所有mp3文件的URL
    NSArray *mp3URLs = [soundBundle URLsForResourcesWithExtension:@"mp3" subdirectory:nil];
    
    // 4.根据每个mp3的URL加载soundID
    for (NSURL *url in mp3URLs){
        SystemSoundID soundID;
        // 5.加载音频ID
        AudioServicesCreateSystemSoundID((__bridge CFURLRef )url, &soundID);
        
        // 6.获得文件名
        NSString *filename = [url.path lastPathComponent];
        
        // 7.将音频ID和文件名放入字典
        [_soundIDs setObject:@(soundID) forKey:filename];
    }
}

#pragma mark 播放背景音乐
- (void)playBgMusic{
    // 1.如果静音，直接返回
    if (_musicMuted) return;
    
    // 2.播放
    [_bgMusicPlayer play];
}

#pragma mark 播放音频
- (void)playSound:(NSString *)soundName{
    // 1.如果静音，直接返回
    if (_soundMuted) return;
    
    // 2.取出音频ID
    SystemSoundID soundID = [_soundIDs[soundName] unsignedIntValue];
    
    // 3.根据播放音频
    AudioServicesPlaySystemSound(soundID);
}

@end
